<template>
  <div class="pay">
    <el-row>
      <el-col :lg="24" style="padding: 10px">
        <el-card class="box-card">
          <div class="t_t">
            <b>余额</b>：￥{{ useryue }}
          </div>
          <div class="t_b">
            <el-row>
              <el-col :lg="16" :md="14" :sm="24" style="padding: 0 0 10px;">
                <el-button :type="v.type" v-for="v in tag" plain style="margin: 10px 10px 0 0" @click="sub(v.num)">{{ v.label }}</el-button>
              </el-col>
              <el-col :lg="8" :md="10" :sm="13" style="padding: 10px 0 0;border-top: 1px dashed #EBEDF3;position: relative;top: -0.5px">
                <el-input-number style="margin-right: 10px;margin-bottom: 10px" :precision="2" v-model="amount" :min="1" :max="10000" :step="0.01" ></el-input-number>
                <el-button type="primary" @click="sub(amount)" :loading="zfloding">{{zfloding?'充值中':'充值'}}</el-button>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :lg="24" style="padding: 10px">
        <el-card class="box-card">
          <el-row  style="margin: 0 0 15px">
            <el-col :xs="24" :sm="10" :md="8" :lg="6">
              <el-input
                  placeholder="搜索"
                  prefix-icon="el-icon-search"
                  clearable
                  @input="searchGo"
                  v-model="search">
              </el-input>
            </el-col>
            <div class="fill hidden-sm-and-up"></div>
            <el-col :xs="24" :sm="13" :md="10" :lg="7" style="display: flex;align-items: center">
              <span style="margin-left: 40px;white-space: nowrap" class="hidden-xs-only">类型：</span>
              <el-select v-model="orderBy">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-table
              class="hidden-xs-only"
              fit
              :data="order_history"
              v-loading="table_loading"
              style="width: 100%"
              @row-click="goAgainPay"
              highlight-current-row>
            <el-table-column
                prop="id"
                label="订单编号"
                min-width="150px"
            >
            </el-table-column>
            <el-table-column
                prop="begintimestamp"
                label="创建时间"
                min-width="160px"
            >
            </el-table-column>
            <el-table-column
                prop="amount"
                label="金额"
                min-width="60px"
            >
            </el-table-column>
            <el-table-column
                label="状态"
                min-width="80px"
            >
              <template slot-scope="scope">
                <el-tag color="#FFF4DE" type="info" v-if="scope.row.state==0">等待支付</el-tag>
                <el-tag color="#C9F7F5" type="success" v-else-if="scope.row.state==1">支付成功</el-tag>
                <el-tag color="#D1D3E0" type="danger" v-else-if="scope.row.state==2">订单已关闭</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              class="hidden-xs-only"
              style="margin: 12px 0px;float: right"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[5,10,15,20,30,40,50]"
              :page-size="pages"
              layout="total, sizes, prev, pager, next, jumper"
              :total="all"
          >
          </el-pagination>

          <el-table
              ref="mytable"
              fit
              :data="order_history"
              style="width: 100%"
              class="m_table hidden-sm-and-up"
              v-loading="table_loading"
              @row-click="row_click_event"
              highlight-current-row>
            <el-table-column type="expand" width="20px">
              <template slot-scope="props">
                <div class="content">
                  <div class="item">
                    <div class="l">订单号：</div>
                    <div class="r">
                      <span>{{ props.row.id }}</span>
                    </div>
                  </div>
                  <div class="item">
                    <div class="l">创建时间：</div>
                    <div class="r">
                      <span>{{ props.row.begintimestamp }}</span>
                    </div>
                  </div>
                  <div class="item" v-if="props.row.state==0">
                    <el-button type="primary" size="small" @click="againPay(props.row.id)">立即前往支付</el-button>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                prop="amount"
                label="金额"
                min-width="80px"
            >
            </el-table-column>
            <el-table-column
                label="状态"
                min-width="50px"
            >
              <template slot-scope="scope">
                <el-tag color="#FFF4DE" type="info" v-if="scope.row.state==0">等待支付</el-tag>
                <el-tag color="#C9F7F5" type="success" v-else-if="scope.row.state==1">支付成功</el-tag>
                <el-tag color="#D1D3E0" type="danger" v-else-if="scope.row.state==2">订单已关闭</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              class="hidden-sm-and-up m_page"
              style="margin: 12px 0px;float: right"
              background
              small
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-size="pages"
              layout="prev, pager, next"
              :total="all"
          >
          </el-pagination>

        </el-card>
      </el-col>
    </el-row>
    <div class="wx_bind_pop" v-if="wxpop">
      <div class="wx_bind_pop_main">
        <div class="wx_bind_pop_title">
          <p>未绑定微信，无法使用微信支付</p>
          <p>点击下方快捷绑定微信</p>
          <p>绑定后还可以使用微信快捷登录</p>
        </div>
        <div class="wx_bind_pop_btn" @click="wxBind">
          <div class="wx_bind_pop_btn_text">
            微信一键绑定
          </div>
        </div>
      </div>
    </div>
    <div class="wx_order_pop" v-if="orderpop">
      <div class="wx_order_pop_main" v-if="$route.query.weyout_trade_no">
        <div class="wx_bind_pop_title">等待付款中...</div>
        <div class="btns" style="display: flex;flex-wrap: wrap;justify-content: center;">
          <el-button type="primary" @click="getWxRes" :loading="yfkloding" style="margin-bottom: 10px">{{yfkloding?'正在向微信询问结果':'我已付款成功'}}</el-button>
          <el-button type="danger" @click="closepop" style="margin-bottom: 10px">关闭弹窗</el-button>
        </div>
      </div>
      <div class="wx_order_pop_main" v-if="$route.query.wenout_trade_no">
        <div class="wx_bind_pop_title">订单支付失败...</div>
        <div class="btns">
          <el-button type="primary" @click="againPay($route.query.wenout_trade_no)" :loading="againloading">{{againloading?'重新支付中':'重新支付'}}</el-button>
          <el-button type="danger" @click="orderpop=false">关闭弹窗</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getWxPay,
  getWxPayHistory,
  getWxPayRes,
  getWxPayState,
  getWxPayUrl,
  userWxBind
} from "../../utils/api";
import qs from "qs";
import util from '../../utils/time'
import {mapState} from "vuex";

export default {
  name: "WxPay",
  data(){
    return {
      tag:[
        { type: 'info', label: '￥10',num:10 },
        { type: 'info', label: '￥30',num:30 },
        { type: 'success', label: '￥50',num:50 },
        { type: 'success', label: '￥100',num:100 },
        { type: 'primary', label: '￥200',num:200 },
        { type: 'primary', label: '￥500',num:500 },
        { type: 'warning', label: '￥1000',num:1000 },
        { type: 'warning', label: '￥5000',num:5000 }
      ],
      amount:1,
      wxpop:false, //微信授权弹框
      orderpop:false, //订单完成弹框
      zfloding:false, //支付加载
      yfkloding:false, //已支付加载
      againloading:false, //重新支付加载
      xintiao:null, //心跳查询
      order_history:[],
      search:'',
      options:[
        {value:'1',label:'全部'},
        {value:'2',label:'等待支付'},
        {value:'3',label:'支付成功'},
        {value:'4',label:'关闭'},
      ],
      orderBy:'1',
      page:1,
      pages:10,
      all:0,
      table_loading:true,
      axiosTime:null,
    }
  },
  methods:{
    sub(v){
      if(this.zfloding){
        this.$notify.error({
          title: '支付提醒',
          message: '正在支付中，请勿点击'
        });
        return;
      }
      let ua = navigator.userAgent.toLowerCase();
      if(ua.indexOf('micromessenger') == -1){
        this.$notify.error({
          title: '警告',
          message:'请在手机微信打开'
        });
        return
      }
      this.zfloding = true
      getWxPay(qs.stringify({title:'余额充值',total:v})).then(res=>{
        if(res.status==200){
          window.location.href = res.body
        }else if(res.status==151){
          this.wxpop = true
        }else {
          this.$notify.error({
            title: '错误',
            message: res.msg
          });
        }
      }).catch(err=>{
        console.log(err)
      })
    },
    wxBind(){
      window.location.replace("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx325d8a04a600270c&redirect_uri="+window.location.origin+'/user/pay' +
          "&response_type=code&scope=snsapi_userinfo&state=cc#wechat_redirect")
    },
    getWxRes(){
      if(this.$route.query.wenout_trade_no || this.$route.query.weyout_trade_no){
        this.zfloding = true
        this.yfkloding = true
        getWxPayRes(qs.stringify({id:this.$route.query.wenout_trade_no || this.$route.query.weyout_trade_no})).then(res=>{
          this.zfloding = false
          this.orderpop = false
          this.yfkloding = false
          if(res.status==200){
            if(res.body.state==1){
              this.$store.commit('setUseryue',(this.useryue-0+('1000'-0)).toFixed(2)-0)
              this.$notify.success({
                title: '支付提醒',
                message: '支付成功'
              });
            }else{
              this.$notify.error({
                title: '支付提醒',
                message: '订单未支付，如有疑问请联系管理员'
              });
            }
          }else{
            this.$notify.error({
              title: '支付提醒',
              message: res.msg
            });
          }
        }).catch(err=>{
          console.log(err)
        })
      }else{
        //没有订单号
        this.$notify.error({
          title: '温馨提示',
          message: '请前往下方订单记录中查看详情'
        });
      }
    },
    againPay(ddh){
      if(ddh){
        this.zfloding = true
        this.againloading = true
        getWxPayUrl(qs.stringify({ddh})).then(res=>{
          this.againloading = false
          if(res.status==200){
            window.location.href = res.body
          }else{
            this.$notify.error({
              title: '错误',
              message: res.msg
            });
          }
        }).catch(err=>{
          console.log(err)
        })
      }else{
        this.$notify.error({
          title: '错误',
          message: '请前往下方订单记录中重新支付'
        });
      }
    },
    closepop(){
      clearInterval(this.xintiao)
      this.orderpop=false
    },
    row_click_event(row){
      this.$refs.mytable.toggleRowExpansion(row)
    },
    goAgainPay(row){
      if(row.state==0){
        this.againPay(row.id)
      }
    },
    searchGo(v){
      if(this.axiosTime!=null){
        clearTimeout(this.axiosTime)
      }
      this.axiosTime = setTimeout(()=>{
        if(this.page==1){
          this.getHistory(this.page,this.pages,this.orderBy,v  || undefined,this.$route.query?.userid)
        }else{
          this.page = 1
        }
      },1000)
    },
    handleSizeChange(size){
      this.pages = size;
      // console.log(this.pagesize); //每页下拉显示数据
    },
    handleCurrentChange(currentPage){
      this.page = currentPage;
      // console.log(this.currentPage); //点击第几页
    },
    getHistory(page,pages,type,like,uid){
      this.table_loading = true
      getWxPayHistory({page,pages,type,like,uid}).then(res=>{
        this.all = res.all
        this.order_history = res.body
        let _t = new Date().getTime()-2*60*60*1000
        this.order_history.forEach(v=>{
          if(v.begintimestamp<=_t && v.state==0){
            v.state = 2
          }
          v.begintimestamp = util.timestampToTime(v.begintimestamp,5)
        })
        this.table_loading = false
      }).catch(err=>{
        console.log(err)
      })
    },
  },
  created() {
    this.getHistory(this.page,this.pages,this.orderBy,this.search || undefined,this.$route.query?.userid)
    let ua = navigator.userAgent.toLowerCase();
    if(ua.indexOf('micromessenger') == -1){
      return
    }
    /*如果存在code 并且用户已经登录 是微信环境 则是微信绑定事件*/
    if(this.$route.query.code && localStorage.getItem('userToken')){
      userWxBind(qs.stringify({code:this.$route.query.code})).then(res=>{
        delete this.$route.query.code;
        if(res.status==200){
          this.$notify.success({
            title: '温馨提示',
            message: res.msg+',请重新下单'
          });
        }else{
          this.$notify.error({
            title: '温馨提示',
            message: res.msg
          });
        }
      }).catch(err=>{
        console.log(err)
      })
    }
    if(this.$route.query.weyout_trade_no){
      //订单支付成功 心跳查询
      this.zfloding = true
      if(this.xintiao==null){
        this.xintiao = setInterval(()=>{
          getWxPayState(qs.stringify({id:this.$route.query.weyout_trade_no})).then(res=>{
            if(res.status==200){
              if(res.body.state==0){
                //订单未支付 需要主动向微信获取结果 并且继续持续获取最新状态
                this.orderpop = true
              }else if(res.body.state==1){
                //订单支付成功
                this.orderpop = false
                this.zfloding = false
                this.$store.commit('setUseryue',(this.useryue-0+('1000'-0)).toFixed(2)-0)
                this.$notify.success({
                  title: '支付提醒',
                  message: '支付成功'
                });
                clearInterval(this.xintiao)
              }
            }
          }).catch(err=>{
            console.log(err)
          })
        },3000)
      }
    }
    if(this.$route.query.wenout_trade_no){
      //订单支付失败 提示失败
      this.zfloding = false
      this.orderpop = true
/*      this.$notify.error({
        title: '支付提醒',
        message: '订单未支付'
      });*/
    }
  },
  computed: {
    ...mapState([
      "useryue",
    ])
  },
  watch:{
    page(){
      if(this.axiosTime!=null){
        clearTimeout(this.axiosTime)
      }
      this.axiosTime = setTimeout(()=>{
        this.getHistory(this.page,this.pages,this.orderBy,this.search  || undefined,this.$route.query?.userid)
      },0)
    },
    pages(){
      if(this.axiosTime!=null){
        clearTimeout(this.axiosTime)
      }
      this.axiosTime = setTimeout(()=>{
        this.getHistory(this.page,this.pages,this.orderBy,this.search || undefined,this.$route.query?.userid)
      },0)
    },
    orderBy(){
      if(this.page==1){
        this.getHistory(this.page,this.pages,this.orderBy,this.search || undefined,this.$route.query?.userid)
      }else{
        this.page = 1
      }
    }
  }
}
</script>

<style scoped>
.pay{

}
.t_t{
  border-bottom: 1px dashed #EBEDF3;
  font-size: 18px;
  padding: 0 0 10px;
}
.wx_bind_pop{
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.25);
  z-index: 999;
}
.wx_bind_pop_main{
  width: 50%;
  min-width: 300px;
  background: #ffffff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border-radius: 10px;
  box-shadow: 6px 4px 10px rgba(0, 0, 0, 0.4);
}
.wx_bind_pop_title p{
  padding: 0;
  margin: 10px 0 0 0;
  text-align: center;
  font-size: 4vw;
}
.wx_bind_pop_btn{
  width: 80%;
  height: 50px;
  background: #0CD55F url("../../assets/wxbind.png") calc(50% - 60px) 50%/40px 40px no-repeat;
  padding-left: 32%;
  margin: 20px auto;
  border-radius: 8px;
}
.wx_bind_pop_btn_text{
  font-size: 16px;
  color: white;
  width: 120px;
  line-height: 50px;
  white-space: nowrap;
}
.wx_order_pop{
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.25);
  z-index: 999;
}
.wx_order_pop_main{
  width: 50%;
  min-width: 300px;
  background: #ffffff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border-radius: 10px;
  box-shadow: 6px 4px 10px rgba(0, 0, 0, 0.4);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 20px;
}
.wx_bind_pop_title{
  padding: 10px 0;
  margin: 10px 0 ;
  text-align: center;
  font-size: 4vw;
}
.content{
  width: 90%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}
.content .item{
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.el-tag{
  border: none;
  height: 24px;
  line-height: 24px;
}
.el-tag--success{
  color: #1BC5BD;
}
.el-tag--info{
  color: #FFA800;
}
.el-tag--danger{
  color: #181C32;
}
.fill{
  width: 100%;
  height: 10px;
  float: left;
}
.el-select{
  width: 100%;
}
/deep/ .el-loading-mask{
  z-index: 1888;
}
</style>
